<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {md5} from 'js-md5';
import {onMounted, reactive, ref} from 'vue'
import {Location, Phone} from '@element-plus/icons-vue'
import {regionData} from 'element-china-area-data'
import {useUserStore} from "@/stores/userStore";
import {CascaderProps, ElMessage, ElMessageBox} from 'element-plus'
import {
  updateUserInfo,
  getUserAddresses,
  addAddress,
  updateUserAddress,
  deleteAddress,
} from "@/router/api";

interface Address {
  id: number;
  accept: string
  telphone: string
  province: string
  city: string
  area: string
  street: string
  def: 'Y' | 'N'
}

const route = useRoute();
const router = useRouter(); // 获取路由实例
const radio = ref(1)
const userId = route.params.id;// 用户ID
const userStore = useUserStore().userInfo;// 用户信息
// 级联选择器配置
const cascaderProps: CascaderProps = {
  value: 'label',
  label: 'label',
  children: 'children'
}
// 验证规则
const rules = {
  accept: {required: true, message: '请输入收件人姓名', trigger: 'blur'},
  telphone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  region: {required: true, message: '请选择省市区', trigger: 'blur'},
}
const showMessage = (type: any, message: any) => {// 显示消息提示
  ElMessage({
    type,
    message,
    duration: 1000,
  });
};
// 修改状态管理
const editState = reactive({
  dialog: false,
  original: null as Address | null,
  form: null as Address | null,
  cascader: [] as string[]
})
// 添加状态管理
const addState = reactive({
  dialog: false,
  form: {
    accept: '',
    telphone: '',
    province: '',
    city: '',
    area: '',
    street: '',
    def: 'N'
  },
  cascader: [] as string[]
})

// 地址数据
const addressList = ref<Address[]>([])
onMounted(() => {
  getAddressList()
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
})
// 地址操作逻辑
const openEdit = (address: Address) => {
  editState.original = address
  editState.form = JSON.parse(JSON.stringify(address))
  editState.cascader = [address.province, address.city, address.area]
  editState.dialog = true
}
//获取所有地址
const getAddressList = async () => {
  try {
    const res = await getUserAddresses(userId)
    addressList.value = Array.isArray(res) ? res : []
  } catch (err) {
    showMessage('error', '获取地址失败')
  }
}
//添加地址
const handleAdd = async () => {
  try {
    await addAddress(userId, addState.form)
    showMessage('success', '添加地址成功')
    addState.dialog = false
    await getAddressList()
    resetAddForm()
  } catch (err) {
    showMessage('error', '添加地址失败')
  }
}
//修改地址
const handleEdit = async () => {
  try {
    await updateUserAddress(userId, editState.original.id, editState.form)
    await getAddressList()
    resetEditForm()
    showMessage('success', '修改地址成功')
    editState.dialog = false
  } catch (err) {
    showMessage('error', '修改地址失败')
  }
}
//删除地址
const handleDelete = (addressId: number) => {
  ElMessageBox({
    title: '删除地址',
    message: '你确定要删除该地址吗？',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    center: true,  // 中心对齐
  }).then(async () => {
    await deleteAddress(addressId)
    showMessage('success', '删除成功');
    await getAddressList()
  }).catch(() => {
    showMessage('info', '已取消删除');
  });
}
// 地址处理逻辑
const combineAddress = (address: Address) => {
  return [address.province, address.city, address.area, address.street].filter(part => part?.trim()).join('-');
}
// 省市区数据
const handleRegionChange = (value: string[]) => {
  const target = editState.dialog ? editState.form : addState.form
  if (value.length === 3 && target) {
    target.province = value[0]
    target.city = value[1]
    target.area = value[2]
  }
}

// 表单编辑重置
const resetEditForm = () => {
  editState.form = null
  editState.cascader = []
}
// 表单添加重置
const resetAddForm = () => {
  addState.form = {
    accept: '',
    telphone: '',
    province: '',
    city: '',
    area: '',
    street: '',
    def: 'N'
  }
  addState.cascader = []
}


const editUserInfoDialog = ref(false)
const errMsg = ref('');
const editUserInfoForm = reactive({
  id: userStore.id,
  account: '',
  email: '',
  telphone: '',
  avatar: '',
  password: '',//新密码
  confirmPassword: '',//确认密码
  code: '',//验证码
  oldTelphone: '',//旧手机号
})
const oldPassword = ref('')// 旧密码
/*const confirmPassword = ref('')// 确认密码*/
const editImgSuccess = (response: any) => {
  if (response.status === "success") { // 与后端响应格式对应
    editUserInfoForm.avatar = response.data; // 直接获取返回的URL
  } else {
    console.error('上传失败:', response.message);
  }
};
const editUserInfoFormRef = ref(null);
const editUserInfoRules = {
  avatar: {required: true, message: '请上传头像', trigger: 'blur'},
  email: {type: 'email', message: '请输入正确的邮箱', trigger: 'blur'},
  code: {required: true, message: '请输入验证码', trigger: 'blur'},
  account: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {min: 6, max: 10, message: '账号长度必须为6到10个字符', trigger: 'blur'},
    {pattern: /^[a-zA-Z][a-zA-Z0-9]{5,9}$/, message: '账号以字母开头且只能是字母和数字', trigger: 'blur'}
  ],
  telphone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  oldTelphone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 10, message: '密码长度必须为6到10个字符', trigger: 'blur'},
    {pattern: /^[A-Z][a-zA-Z0-9]{5,9}$/, message: '密码以大写字母开头且只能是字母和数字', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {validator: (rule: any, value: any, callback: any) => {
        if (value !== editUserInfoForm.password) {
          callback('两次输入的密码不一致!');
        } else {
          callback();
        }
      }, trigger: 'blur'
    },
  ],
}
//重置修改个人信息表单
const resetEditUserInfoForm = () => {
  // 只重置修改相关字段，保留当前用户信息
  editUserInfoForm.password = '';
  editUserInfoForm.code = '';
  editUserInfoForm.telphone = '';
  editUserInfoFormRef.value?.resetFields();
  errMsg.value = '';
  oldPassword.value = '';
  editUserInfoForm.confirmPassword = '';

  // 保持其他字段为最新值
  editUserInfoForm.id = userStore.id;
  editUserInfoForm.account = userStore.account;
  editUserInfoForm.email = userStore.email;
  editUserInfoForm.oldTelphone = userStore.telphone;
  editUserInfoForm.avatar = userStore.avatar;
}
const handleEditUserInfo = async () => {
  let dataToUpdate: any = {id: userStore.id}; // 始终包含用户ID

  // 根据radio的值进行不同字段的验证和数据收集
  if (radio.value === 1) {
    if (editUserInfoForm.code !== currentCode.value) {
      errMsg.value = "验证码错误";
      return;
    }
    if (editUserInfoForm.oldTelphone !== userStore.telphone) {
      errMsg.value = "请输入正确的旧手机号";
      return;
    }
    dataToUpdate.telphone = editUserInfoForm.telphone;
    dataToUpdate.password = '';
    dataToUpdate.avatar = userStore.avatar;
    dataToUpdate.email = userStore.email;
    dataToUpdate.account = userStore.account;

  } else if (radio.value === 2) {
    // 检查旧密码是否正确
    const oldPasswordHash = md5(oldPassword.value);
    if (oldPasswordHash !== userStore.password) {
      errMsg.value = "原密码错误";
      return;
    }
    if (editUserInfoForm.password !== editUserInfoForm.confirmPassword) {
      errMsg.value = "两次密码输入不一致";
      return;
    }
    dataToUpdate.password = editUserInfoForm.password;
    dataToUpdate.avatar = userStore.avatar;
    dataToUpdate.email = userStore.email;
    dataToUpdate.account = userStore.account;
    dataToUpdate.telphone = userStore.telphone;

  } else if (radio.value === 3) {
    dataToUpdate.avatar = editUserInfoForm.avatar;
    dataToUpdate.email = editUserInfoForm.email;
    dataToUpdate.account = editUserInfoForm.account;
    dataToUpdate.telphone = userStore.telphone;
    dataToUpdate.password = '';
  }

  try {
    // 保存修改前的原始值
    const originalTel = userStore.telphone;
    const originalPassword = userStore.password;
    const originalAccount = userStore.account;

    // 调用API，只传递必要字段
    await updateUserInfo(dataToUpdate)
    showMessage('success', '修改个人信息成功')
    userStore.avatar = dataToUpdate.avatar;
    userStore.email = dataToUpdate.email;
    userStore.account = dataToUpdate.account;
    userStore.telphone = dataToUpdate.telphone;
    if (dataToUpdate.password !== '') {
      userStore.password = md5(dataToUpdate.password);
    }
    // 检查字段是否被修改
    const telChanged = dataToUpdate.telphone !== undefined && dataToUpdate.telphone !== originalTel;
    const passwordChanged = dataToUpdate.password !== '' && md5(dataToUpdate.password) !== originalPassword;
    const accountChanged = dataToUpdate.account !== undefined && dataToUpdate.account !== originalAccount;

    // 如果任一字段被修改，跳转到登录界面
    if (telChanged || passwordChanged || accountChanged) {
      await router.replace('/login-register'); // 使用路由跳转
      const u = useUserStore();
      u.logout();
    }

    editUserInfoDialog.value = false
    resetEditUserInfoForm()
  } catch (err) {
    showMessage('error', '修改个人信息失败')
    resetEditUserInfoForm()
  }
}
const openModal = () => {
  editUserInfoDialog.value = true;

  // 强制从store同步最新数据到表单
  editUserInfoForm.id = userStore.id;
  editUserInfoForm.account = userStore.account;
  editUserInfoForm.email = userStore.email;
  editUserInfoForm.avatar = userStore.avatar;
  editUserInfoForm.oldTelphone = userStore.telphone;

  // 仅清空需要输入的字段
  editUserInfoForm.telphone = '';
  editUserInfoForm.password = '';
  editUserInfoForm.code = '';

  editUserInfoFormRef.value?.resetFields();
  errMsg.value = '';
  oldPassword.value = '';
  editUserInfoForm.confirmPassword = '';
}

// 发送验证码
const sendingCode = ref(false);
const countdown = ref(0);
const currentCode = ref('');
const timer = ref(null);
const handleSendCode = async () => {
  // 触发表单验证
  if (!editUserInfoFormRef.value) return;
  const valid = await editUserInfoFormRef.value.validateField('oldTelphone');
  if (!valid) return;

  if (sendingCode.value) return;
  sendingCode.value = true;
  const userStore = useUserStore();

  try {
    const code = await userStore.sendCodeByPhone(editUserInfoForm.oldTelphone);
    currentCode.value = code

    // 启动倒计时
    countdown.value = 60;
    timer.value = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer.value);
        timer.value = null;
      }
    }, 1000);

    if (editUserInfoForm.oldTelphone === userStore.userInfo.telphone) {
      // 使用现代剪贴板API
      if ('clipboard' in navigator) {
        await navigator.clipboard.writeText(code);
      }

      // 尝试自动填充验证码（如果表单中有验证码输入框）
      setTimeout(() => {
        editUserInfoForm.code = code;
        editUserInfoFormRef.value?.scrollToField('code');
      }, 300);

      ElMessage.success(`您的验证码是：${code}`);
    }
  } catch (error) {
    ElMessage.error('验证码发送失败，请稍后再试');
  } finally {
    sendingCode.value = false;
  }
};
</script>


<template>
  <div class="account-container">
    <!-- 个人信息 -->
    <div class="user-info">
      <h2>个人信息
        <el-button type="primary" @click="openModal">修改个人信息</el-button>
        <el-button type="warning" @click="addState.dialog = true" class="add-address-btn">
          添加地址
        </el-button>
      </h2>
      <el-descriptions border>
        <el-descriptions-item label="头像" :rowspan="2" label-align="center" width="100">
          <el-image style="width: 100px; height: 100px" :src="userStore.avatar"/>
        </el-descriptions-item>
        <el-descriptions-item label="账号" label-align="center">{{ userStore.account }}</el-descriptions-item>
        <el-descriptions-item label="邮箱" label-align="center">{{ userStore.email }}</el-descriptions-item>
        <el-descriptions-item label="电话" label-align="center">{{ userStore.telphone }}</el-descriptions-item>
        <el-descriptions-item label="积分" label-align="center">
          <el-tag type="warning">{{ userStore.points }} 积分</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态" label-align="center" align="center">
          <el-tag type="warning">{{ userStore.status === "1" ? '正常' : '冻结' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="登录时间" label-align="center">{{
            userStore.last_login_time
          }}
        </el-descriptions-item>
        <el-descriptions-item label="登录地点" label-align="center">{{ userStore.last_login_ip }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 地址列表 -->
    <div class="address-list">
      <h2>收货地址</h2>
      <el-empty v-if="addressList.length === 0" :image-size="100" description="暂无地址"/>
      <div v-else class="address-items">
        <el-card
            v-for="address in addressList"
            :key="address.id"
            shadow="hover"
            class="address-card">
          <template #header>
            <div class="card-header">
              <span>{{ address.accept }}</span>
              <el-tag v-if="address.def === 'Y'" type="warning" size="small">默认地址</el-tag>
              <el-button @click="openEdit(address)" plain type="primary" size="small" style="margin-left: auto">
                修改地址
              </el-button>
              <el-button :disabled="address.def === 'Y'" @click="handleDelete(address.id)" plain type="danger"
                         size="small" style="margin-left: 5px">
                删除地址
              </el-button>
            </div>
          </template>
          <div class="address-content">
            <div class="address-detail">
              <el-icon>
                <Location/>
              </el-icon>
              {{ combineAddress(address) }}
            </div>
            <div class="address-phone">
              <el-icon>
                <Phone/>
              </el-icon>
              {{ address.telphone }}
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
        title="修改地址"
        center draggable
        v-model="editState.dialog"
        @closed="resetEditForm">
      <el-form :model="editState.form" :rules="rules" v-if="editState.form">
        <el-form-item label="收件人" prop="accept">
          <el-input v-model="editState.form.accept"/>
        </el-form-item>
        <el-form-item label="手机号" prop="telphone">
          <el-input v-model="editState.form.telphone"/>
        </el-form-item>
        <el-form-item label="省市区" prop="region">
          <el-cascader
              v-model="editState.cascader"
              :options="regionData"
              :props="cascaderProps"
              @change="handleRegionChange"
              placeholder="请选择省市区"
              style="width: 100%"/>
        </el-form-item>
        <el-form-item label="详细地址" prop="street">
          <el-input v-model="editState.form.street"/>
        </el-form-item>
        <el-form-item label="默认地址">
          <el-switch
              v-model="editState.form.def"
              active-value="Y"
              inactive-value="N"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editState.dialog = false">取消</el-button>
        <el-button type="primary" @click="handleEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog
        title="添加地址"
        center draggable
        v-model="addState.dialog"
        @closed="resetAddForm">
      <el-form :model="addState.form" :rules="rules">
        <el-form-item label="收件人" prop="accept">
          <el-input v-model="addState.form.accept"/>
        </el-form-item>
        <el-form-item label="手机号" prop="telphone">
          <el-input v-model="addState.form.telphone"/>
        </el-form-item>
        <el-form-item label="省市区" prop="region">
          <el-cascader
              v-model="addState.cascader"
              :options="regionData"
              :props="cascaderProps"
              @change="handleRegionChange"
              placeholder="请选择省市区"
              style="width: 100%"/>
        </el-form-item>
        <el-form-item label="详细地址" prop="street">
          <el-input v-model="addState.form.street"/>
        </el-form-item>
        <el-form-item label="默认地址">
          <el-switch
              v-model="addState.form.def"
              active-value="Y"
              inactive-value="N"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addState.dialog = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">添加</el-button>
      </template>
    </el-dialog>

    <!-- 修改个人信息 -->
    <el-dialog title="修改个人信息" center draggable
               v-model="editUserInfoDialog" @closed="resetEditUserInfoForm">
      <el-radio-group v-model="radio" style="margin: 20px auto;width: 100%">
        <el-radio :value="1">修改手机号</el-radio>
        <el-radio :value="2">修改密码</el-radio>
        <el-radio :value="3">其他</el-radio>
      </el-radio-group>
      <p v-if="errMsg" style="color: red">{{ errMsg }}</p>
      <el-form :model="editUserInfoForm" :rules="editUserInfoRules" hide-required-asterisk
               status-icon scroll-to-error label-width="auto" size="default" ref="editUserInfoFormRef">
        <el-form-item label="头像" prop="avatar" v-if="radio === 3">
          <el-upload
              action="http://localhost:8080/api/upload-with-replace"
              :show-file-list="false"
              :on-success="editImgSuccess"
              :data="{ oldImageUrl: editUserInfoForm.avatar }"
              name="file">
            <el-avatar size="large" v-if="editUserInfoForm.avatar" :src="editUserInfoForm.avatar"
                       style="border: 1px solid #ccc"/>
            <el-avatar v-else size="large" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                       style="border: 1px solid #ccc"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" v-if="radio === 3">
          <el-input v-model="editUserInfoForm.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="账号" prop="account" v-if="radio === 3">
          <el-input v-model="editUserInfoForm.account" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item label="旧手机号" prop="oldTelphone" v-if="radio === 1">
          <div style="display: flex;flex-direction: row;flex: 1">
            <el-input v-model="editUserInfoForm.oldTelphone" placeholder="请输入手机号"/>
            <el-button
                type="primary"
                :disabled="sendingCode || countdown > 0"
                @click="handleSendCode"
                style="margin-left: 20px;">
              {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="验证码" prop="code" v-if="radio === 1">
          <el-input v-model="editUserInfoForm.code" placeholder="请输入验证码"/>
        </el-form-item>
        <el-form-item label="新手机号" prop="telphone" v-if="radio === 1">
          <el-input v-model="editUserInfoForm.telphone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="请输入旧密码" v-if="radio === 2">
          <el-input v-model="oldPassword" placeholder="请输入旧密码" type="password" show-password/>
        </el-form-item>
        <el-form-item label="请输入新密码" prop="password" v-if="radio === 2">
          <el-input type="password" v-model="editUserInfoForm.password" show-password placeholder="请输入新密码"/>
        </el-form-item>
        <el-form-item label="请确认密码" v-if="radio === 2" prop="confirmPassword">
          <el-input v-model="editUserInfoForm.confirmPassword" placeholder="请确认密码" type="password" show-password/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editUserInfoDialog = false">取消</el-button>
        <el-button type="primary" @click="handleEditUserInfo">修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.account-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.user-info, .address-list {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.address-items {
  display: grid;
  gap: 15px;
}

.address-card {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  gap: 10px;
  align-items: center;
}

.address-content {
  line-height: 1.8;
  color: #666;
}

.address-detail, .address-phone {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>